package controllers;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.Domain;
import server.Get;

import com.google.appengine.api.datastore.Text;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

@SuppressWarnings("serial")
public class RodderboyServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
		
		String path = ((HttpServletRequest)req).getRequestURI();
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 

        if(count != 2)
        {
        	try {
				req.getRequestDispatcher("/").forward(req, resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
        	return;
        }
        
		// skip one token /question/abcd (remove sites)
		st.nextToken();
		String name = st.nextToken();
		name = Utils.fomatDomain(name);
		String result = "This domain is available to register!";
		Domain domain = new Domain();
		if(name!=null&&name.length()>0&&Utils.checkDomain(name))
		{
			try {
				ObjectifyService.register(Domain.class);
			} catch (Exception e) {
				// TODO: handle exception
			}
			Objectify objectify = ObjectifyService.begin();
			
			try {
				resp.setHeader( "Cache-Control", "public, max-age=86400");
				resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
				
				domain = objectify.get(new Key<Domain>(Domain.class, name));
				
				PutCache.putCacheList(domain.getDomain(), "view",18);
				
				req.setAttribute("domain", domain);
			} catch (Exception e) {
				
				domain.setDomain(name);
				
				result = Get.Whois(name);
				domain.setWhois(new Text(Utils.cleanWhois(result)));
				
				PutCache.putCacheList(domain.getDomain(), "view",18);
				
				if(domain.getOtherDomain().length()<10)
				{
					int ran = new Random().nextInt(100000);

			    	Query<Domain> list = objectify.query(Domain.class).filter("rand >", ran).limit(5);
			    	String otherDomain = "";
			    	for (Domain ar: list) {
			    		otherDomain+=ar.getDomain()+",";
			    	}
			    	list = objectify.query(Domain.class).order("-rand").filter("rand <", ran).limit(5);
			    	for (Domain ar: list) {
			    		otherDomain+=ar.getDomain()+",";
			    	}
			    	otherDomain=otherDomain.replaceAll("[,]+$", "");
			    	domain.setOtherDomain(otherDomain);
				}
				
				
				objectify.put(domain);
			}
			
			
		}
		
		req.setAttribute("domain", domain);
		req.setAttribute("name", name);
		
		try {
			req.getRequestDispatcher("/index.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
